#include "config.h"
#include "cicm.cpp"
#include <iostream>

/**
  Decrypt entry point. Executes steps 1 - 3 and 7 - 10 of the test harness scenario.
  @file decrypt.cpp
  @version 0.2
  @date 2011-03-09
*/
int main() {
  CICM::Status s;

  CICM::CICMRoot           *root = new CICM::CICMRoot();
  CICM::ModuleId            module_id = (char*) V_MODULE_ID;
  CICM::CryptoModule       *crypto_mod;
  CICM::SymKeyManager      *sym_key_manager;
  CICM::KeyId               key_id = (char*) V_KEY_ID;
  CICM::SymKey             *key;
  CICM::ChannelManager     *chan_manager;
  CICM::RemotePort          port = V_PORT_DECRYPT;
  CICM::SymEncrAlgorithmId  algo = (char*) V_ALGORITHM;
  CICM::Decrypt::Conduit   *conduit;
  CICM::Buffer             *buf;
  CICM::Buffer             *payload = new CICM::Buffer(V_PAYLOAD_LEN, (char*) V_PAYLOAD);

  // Step 1. Retrieve the module with the id {as configured}.
  s = root->get_module_by_id(module_id, &crypto_mod);
  if(S_OK == s) std::cout << "Step 1. Got the module." << std::endl;

  // Step 2. Select the symmetric key manager.
  sym_key_manager = crypto_mod->_get_sym_key_manager();
  std::cout << "Step 2. Got the symmetric key manager." << std::endl;

  // Step 3. Select the symmetric key with the id {as configured}.
  s = sym_key_manager->get_key_by_id(key_id,  &key);
  if(S_OK == s) std::cout << "Step 3. Got the symmetric key." << std::endl;

  std::cout << "(Step 7 is next)" << std::endl;

  // Step 7. Select the channel manager.
  chan_manager = crypto_mod->_get_channel_manager();
  std::cout << "Step 7. Got the channel manager." << std::endl;

  // Step 8. Create a decrypt channel that uses the same algorithm {as configured in step 5}.
  s = chan_manager->create_decrypt_conduit(port, key, algo, &conduit);
  if(S_OK == s) std::cout << "Step 8. Got the conduit." << std::endl;

  // Step 9. Block until ready to receive payload.
  s = conduit->decrypt(&buf);
  if(S_OK == s) std::cout << "Step 9. Decrypted the payload." << std::endl;

  // Step 10. Verify that the result from step 9 is the same as the payload used in step 6.
  std::cout << "Step 10. Payload "
    << ((*buf == *payload) ? "PASS" : "FAIL" ) << "." << std::endl;

  std::cout << "DONE - Decrypt" << std::endl;

  return 0;
}
